<?php
/**
 * Created by PhpStorm.
 * User: surestdeng
 * Date: 2019/12/23
 * Time: 16:36:09
 */

namespace App\Services;

use App\Models\Article;
use App\Repositories\Handler\LearnkuHandler;
use Illuminate\Support\Arr;
use QL\QueryList;

class ZhihukuService
{
    public function run()
    {
        $urls = config('zhihu.list');
        $articles = [];

        foreach ($urls as $url => $tag) {
            $data = QueryList::Query($url, [
                'avatar' => ['.HotItem-title', 'html']
            ])->data;

            # 过滤
            $articles = array_map(function ($article) {
                $article['title'] = compress_html($article['title']);
                return $article;
            }, $articles);

            $learkn = new LearnkuHandler();
            $articles = $learkn->handle($articles, 'Learnku');

            $this->insert($articles, $learkn);
        }
    }

    public function insert(array $articles, LearnkuHandler $learnkuHandler)
    {
        logEcho($articles, 'learnku.log');
        Article::query()->insert($articles);
        $learnkuHandler->save($articles);
    }
}
